import axios from 'axios'
import router from '../router'

export const http = axios.create({
  baseURL: '/',
})

export function setAuthHeader(username: string, password: string) {
  const token = btoa(`${username}:${password}`)
  http.defaults.headers.common['Authorization'] = `Basic ${token}`
  localStorage.setItem('bm_auth', token)
}

export function restoreAuth() {
  const token = localStorage.getItem('bm_auth')
  if (token) {
    http.defaults.headers.common['Authorization'] = `Basic ${token}`
  }
}

export function clearAuth() {
  delete http.defaults.headers.common['Authorization']
  localStorage.removeItem('bm_auth')
}

http.interceptors.response.use(
  (resp) => resp,
  (err) => {
    if (err?.response?.status === 401) {
      clearAuth()
      router.push('/login')
    }
    return Promise.reject(err)
  }
)